package v1

import (
	"github.com/gin-gonic/gin"
	"hytx_media/models"
	"hytx_media/pkg/app"
	"net/http"
	"hytx_media/pkg/e"
	"hytx_media/service/comment_service"
	"github.com/Unknwon/com"
)

func GetComments(c *gin.Context) {
	user := c.MustGet("user").(*models.MediaUser)
	ag := app.Gin{C:c}
	page := 1
	if arg := c.Query("p"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	id := com.StrTo(c.Param("id")).MustInt()
	comments, paginate := comment_service.GetComments(id, user.ID, page, 10)

	data := make(map[string]interface{})
	data["data"] = comments
	data["total"] = paginate.Total()
	data["count"] = paginate.Count
	data["current"] = paginate.Page
	ag.Response(http.StatusOK, e.SUCCESS, data)
}

func GetCommentNumList(c *gin.Context) {
	user := c.MustGet("user").(*models.MediaUser)
	ag := app.Gin{C:c}
	page := 1
	if arg := c.Query("p"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	result, paginate := comment_service.GetCommentNumList(user.ID, page, 10)

	data := make(map[string]interface{})
	data["data"] = result
	data["total"] = paginate.Total()
	data["count"] = paginate.Count
	data["current"] = paginate.Page
	ag.Response(http.StatusOK, e.SUCCESS, data)
}
/**
	置顶
 */
func CommentStick(c *gin.Context) {
	//取消之前所有置顶
	//文章id
	aid := com.StrTo(c.Param("id")).MustInt()
	db := models.DB.Begin()
	err := db.Table("comments").Where("a_id=?", aid).Update("is_stick", 0).Error
	if err != nil {
		db.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": e.Error,
			"msg": e.GetMsg(e.Error),
		})
		return
	}
	//评论id
	cid := com.StrTo(c.Param("cid")).MustInt()
	//置顶
	err = db.Table("comments").Where("id=?", cid).Update("is_stick", 1).Error
	if err != nil {
		db.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": e.Error,
			"msg": e.GetMsg(e.Error),
		})
		return
	}
	db.Commit()
	c.JSON(http.StatusCreated, gin.H{
		"code": e.SUCCESS,
		"msg": e.GetMsg(e.SUCCESS),
	})
}

func CommentFeedback(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	user := c.MustGet("user").(*models.MediaUser)

	t := c.PostForm("type")
	content := c.PostForm("content")
	feed := models.CommentFeedback{
		MediaUserId: user.ID,
		CId:id,
		Type: t,
		Content: content,
	}
	models.DB.Create(&feed)
	c.JSON(http.StatusCreated, gin.H{
		"code": e.SUCCESS,
		"msg": e.GetMsg(e.SUCCESS),
	})
}